import scala.concurrent._
import scala.concurrent.duration._
//import ExecutionContext.Implicits.global
import java.util.concurrent.Executors

import java.net._;
import java.nio._;

import java.util._;

object Server extends App 
{  
  
  implicit val ec = new ExecutionContext {
    val threadPool = Executors.newFixedThreadPool(100);

    def execute(runnable: Runnable) {
        threadPool.submit(runnable)
    }

    def reportFailure(t: Throwable) {}
  }
  
  
  var serverSocket = new ServerSocket(5555);
  
  while (true)
  {
    var socket = serverSocket.accept();
    val f : Future[String] = future 
    {
	  var in = new java.io.DataInputStream(socket.getInputStream());
	  var out = new java.io.DataOutputStream(socket.getOutputStream());
	  
	  var running = true
	  while (running)
	  {
	    var r = in.readInt();
	    if (r == -99)
	    {
	      in.close();
	      out.close();
	      socket.close();
	      running = false;
	    }
	    else
	    {
		    r = r + 1;
		    out.writeInt(r);
	    }
	  }
	  
	  "Closed"
  	}
  
  	f onSuccess {
  		case msg => println(msg)
  	}
    
  }
  
   /*
	var serverSocket = new ServerSocket(5555);
	
	var socket = serverSocket.accept();
    var in = new java.io.DataInputStream(socket.getInputStream());
    var out = new java.io.DataOutputStream(socket.getOutputStream());
	    
	while (true)
	{
	    var r = in.readInt();
	    println ("read from client:" + r);
	    if (r == -99)
	    {
	      in.close();
	      out.close();
	      socket.close();
	      
	      socket = serverSocket.accept();
	      in = new java.io.DataInputStream(socket.getInputStream());
	      out = new java.io.DataOutputStream(socket.getOutputStream());
	    }
	    else
	    {
		    r = r + 1;
		    out.writeInt(r);
		    println ("sent to client:" + r);
	    }
  
  
  
  
  
	    r = r + 1;
	    println (r);
	    out.write(r);
	    println ("sent to client:" + r);
	    
	    r = in.readInt();
	    println ("read from client:" + r);
	    println (r);
	    
	    println ("closing connection");
	    in.close();
	    out.close();
	    socket.close();
	    
	}
    */
}

/*
object main extends App {
  
  val p = new Point;
  p.x = 3;
  p.y = 4;	
  
  val s = "Hello"
  
  var z = new Array[Future[String]](500)
  
  var a = 0;
  for( a <- 0 to 499){
    z(a) = future {
	  s + " future!"
  	}
    
    z(a) onSuccess {
  		case msg => println(msg + a)
  	}
    
    //val f: Future[String] = future {
	//  s + " future!"
  	//}
  
  	//f onSuccess {
  	//	case msg => println(msg + a)
  	//}
  }
  
  println ("Point x location : " + p.max());
 
  for( a <- 0 to 499){
    Await.result(z(a), 0 nanos)
  }
  
  
  //val theInteger = Console.readInt();
  //val theString = Console.readLine();
  
  //println (theInteger);
  //println (theString);
  
	
}

class Point {
  var x = 0;
  var y = 0;
  
  def max(): Int = {
    if 
      (x > y) x
	else 
	  y
  }
}
*/